package cap.action;

import cap.bean.*;
import cap.dao.*;
import cap.dao.impl.*;
import cap.util.PageControl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private UserDao userDao;
    private SysCategoryDao sysCategoryDao;
    private ArticleDao articleDao;
    private BlogInfoDao blogInfoDao;
    private CategoryDao categoryDao;
    private ProfileDao profileDao;
    public UserServlet() {
        userDao=new UserDaoImpl();
        sysCategoryDao=new SysCategoryDaoImpl();
        articleDao=new ArticleDaoImpl();
        blogInfoDao=new BlogInfoDaoImpl();
        categoryDao=new CategoryDaoImpl();
        profileDao=new ProfileDaoImpl();
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf8");
        response.setCharacterEncoding("Utf-8");
        int userId;
        BlogInfo bi;
        String blogName;
        String method = request.getParameter("method");
        if (("index").equals(method)) {//首页
            //跳转到首页
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf8");
            List<SysCategory> sysCategories = sysCategoryDao.getAllSysCategory();//获取所有系统分类
            List<User> users = articleDao.getActiveUser(2);//获取两个活跃用户
            List<Article> tenList = articleDao.topTenArticle();//获取前十博文
            //分页
            String curPage = request.getParameter("curPage");//当前页码
            int count = articleDao.getAllArtical().size();//获取当前页码信息
            int curPageStr=1;
            if(curPage!=null){
                curPageStr=Integer.parseInt(curPage);
            }
            PageControl pc = new PageControl(curPageStr, count);
            List<Article> artList = articleDao.getArticleByPage(curPageStr, count);
            pc.setList(articleDao.getAllArtical());
            request.setAttribute("curPage", pc.getCurPage());
            request.setAttribute("totalPages", pc.getPageSize());
            request.setAttribute("uList", users);
            request.setAttribute("scList", sysCategories);
            request.setAttribute("tenList", tenList);
            request.setAttribute("artList", pc.getList());
            request.getRequestDispatcher("index.jsp").forward(request, response);
        } else if (("myblog").equals(method)) {//我的博客
            //获取所有博文信息
            userId = Integer.parseInt(request.getParameter("userId"));
            bi = blogInfoDao.getByuserId(userId);//个人博客信息
            List<Category> cgList = categoryDao.getByUserId(userId);//获取用户的个人博客分类
            User u = userDao.getUserById(userId);
            if (null == bi) {
                response.sendRedirect("front/404.jsp");
            } else {
                blogName = bi.getBlogName();
                String blogPropagate = bi.getPropagate();
                String curPageStr = request.getParameter("curPage");
                int curPage=1;
                int total=articleDao.getByUserId(userId).size();
                if(curPageStr!=null){
                    curPage=Integer.parseInt(curPageStr);
                }
                PageControl pc = new PageControl(curPage, articleDao.getByUserId(userId).size());//获取作者当前页码博文
                List<Article> artList = articleDao.getArticleByPageUserId(curPage, total, userId);
                pc.setList(articleDao.getByUserId(userId));
                request.setAttribute("userId", userId);
                request.setAttribute("blogName", blogName);
                request.setAttribute("blogAnnoucement", blogPropagate);
                request.setAttribute("artList", pc.getList());
                request.setAttribute("cgList", cgList);
                request.setAttribute("blogInfo", bi);
                request.setAttribute("author", u.getUserName());
                request.setAttribute("curPage", pc.getCurPage());
                request.setAttribute("totalPages", pc.getTotalPages());
                request.getRequestDispatcher("front/MyBlogIndex.jsp").forward(request, response);
            }
        } else if (("myblogFilter").equals(method)) {//获取作者所有博文
            userId = Integer.parseInt(request.getParameter("userId"));
            int categoryId = Integer.parseInt(request.getParameter("categoryId"));
            bi = blogInfoDao.getByuserId(userId);//个人博客信息
            List<Category> cgList = categoryDao.getByUserId(userId);//获取用户的个人分类
            User u = userDao.getUserById(userId);
            if (null == bi) {
                response.sendRedirect("front/404.jsp");
            } else {
                blogName = bi.getBlogName();
                String blogPropagate = bi.getPropagate();

                String curPageStr = request.getParameter("curPage");
                //获取作者当前页码博文
                int curPage=1;
                if(curPageStr!=null){
                    curPage=Integer.parseInt(curPageStr);
                }
                PageControl pc = new PageControl(curPage, articleDao.getByUserId(userId).size());
                int total=articleDao.getByUserId(userId).size();
                List<Article> artList = articleDao.getArticleByPageUserCategoryId(curPage, total, userId, categoryId);
                pc.setList(articleDao.getByUserId(userId));
                request.setAttribute("userId", userId);
                request.setAttribute("blogName", blogName);
                request.setAttribute("blogAnnoucement", blogPropagate);
                request.setAttribute("artList", pc.getList());
                request.setAttribute("cgList", cgList);
                request.setAttribute("blogInfo", bi);
                request.setAttribute("author", u.getUserName());
                request.setAttribute("curPage", pc.getCurPage());
                request.setAttribute("totalPages", pc.getTotalPages());
                request.getRequestDispatcher("front/MyBlogIndex.jsp").forward(request, response);
            }
        } else if (("apply").equals(method)) {
            userId = Integer.parseInt(request.getParameter("userId"));
            blogName = request.getParameter("blog_name");
            String description = request.getParameter("description");
            String annoucement = request.getParameter("annoucement");
            bi = blogInfoDao.getByuserId(userId);
            int res = -1;
            if (null != bi) {
                res = blogInfoDao.updateBlogInfo(userId, blogName, description, annoucement);
                bi = blogInfoDao.getByuserId(userId);
            } else {
                res = blogInfoDao.insertBlogInfo(userId, blogName, description, annoucement);//开通博客
            }
            if (res > 0) {
                userDao.setIsAppliedById(userId);
                //插入默认分类
                categoryDao.insertCategory(userId, "无分类");
                User u = userDao.getUserById(userId);        //查询最新的用户信息
                String succMsg = "申请博客成功！";
                request.getSession().setAttribute("user", u);
                request.getSession().setAttribute("successMsg", succMsg);
            }else {
                String errorMsg = "申请博客失败！";
                request.getSession().setAttribute("errorMsg", errorMsg);
            }
            response.sendRedirect("front/ApplyBlog.jsp");
        }else if(method.equals("profile")){//编辑个人信息
            //转到个人主页
            int id = Integer.parseInt(request.getParameter("id"));
            User u = userDao.getUserById(id);//根据id获取用户资料
            Profile pf = profileDao.getByuserId(id);//根据id获取个人信息
            if (null != pf) {
                request.setAttribute("profile", pf);
            }
            request.getSession().setAttribute("user", u);
            request.getRequestDispatcher("front/Profile.jsp").forward(request, response);
        }else if(method.equals("logout")){//登出
            request.setCharacterEncoding("utf-8");
            HttpSession session = request.getSession(false); //防止创建Session
            if (null == session) {
                response.sendRedirect("user?method=index");
                return;
            }
            session.removeAttribute("user");
            response.sendRedirect("user?method=index");
        }else if(method.equals("myblogindex")){//我的博客
            userId = Integer.parseInt(request.getParameter("userId"));
            bi = blogInfoDao.getByuserId(userId);
            List<Category> cgList = categoryDao.getByUserId(userId);    //获取用户的个人分类
            ArticleDao artDao = new ArticleDaoImpl();
            User u = userDao.getUserById(userId);
            if (null == bi) {
                //跳转到404页面
                response.sendRedirect("front/404.jsp");
            } else {
                blogName = bi.getBlogName();
                String blogAnnoucement = bi.getPropagate();
                String curPageStr = request.getParameter("curPage");
                int curPage=1;
                if(curPageStr!=null){
                    curPage=Integer.parseInt(curPageStr);
                }
                PageControl pc = new PageControl(curPage, artDao.getByUserId(userId).size());
                int total=artDao.getByUserId(userId).size();
                List<Article> artList=artDao.getArticleByPageUserId(curPage, total, userId);
                pc.setList(articleDao.getByUserId(userId));
                request.setAttribute("userId", userId);
                request.setAttribute("blogName", blogName);
                request.setAttribute("blogAnnoucement", blogAnnoucement);
                request.setAttribute("artList", pc.getList());
                request.setAttribute("cgList", cgList);
                request.setAttribute("blogInfo", bi);
                request.setAttribute("author", u.getUserName());
                request.setAttribute("curPage", pc.getCurPage());
                request.setAttribute("totalPages", pc.getTotalPages());
                request.getRequestDispatcher("front/MyBlogIndex.jsp").forward(request, response);
            }
        }else if(method.equals("search")){//搜索站内文章
            String q = request.getParameter("q");
            List<Article> artList = articleDao.search(q);
            request.setAttribute("q", q);
            request.setAttribute("artList", artList);
            request.getRequestDispatcher("front/Search.jsp").forward(request, response);
        }else if(method.equals("updatepass")){//修改密码
            String oldPwd = request.getParameter("old_pwd");
            String newPwd = request.getParameter("new_pwd");
            userId = Integer.parseInt(request.getParameter("userId"));
            User u = userDao.getByIdPwd(userId, oldPwd);//根据userId和password查询用户记录
            if (null != u) {//验证成功，允许更新密码
                int res = userDao.updatePwdById(userId, newPwd);
                if (res > 0) {
                    request.getSession().setAttribute("succUpdateMsg", "修改密码成功！");
                } else {
                    request.getSession().setAttribute("errorUpdateMsg", "修改密码失败！");
                }
            } else {//验证失败
                request.getSession().setAttribute("validPwdMsg", "旧密码验证失败，请重新填写！");
            }
            response.sendRedirect("user?method=profile&id="+userId);
        }else if(method.equals("updateprofile")){//更新个人信息
            userId = Integer.parseInt(request.getParameter("id"));
            String firstName = request.getParameter("first_name");
            String lastName = request.getParameter("last_name");
            String genderVal = request.getParameter("gender");	//取到的是男女 -> 1,0
            int gender = genderVal.equals("male") ? 1 : 0;
            String telephone = request.getParameter("telephone");
            Profile pf = profileDao.getByuserId(userId);
            int res = -1;
            int resOfpf = -1;
            if (null != pf) {
                res = profileDao.updateProfile(userId, firstName, lastName, gender, telephone);//如果有个人信息，则更新
                pf = profileDao.getByuserId(userId);
            } else {
                res = profileDao.insertProfile(userId, firstName, lastName, gender, telephone);//如果无个人信息，则新建
            }
            if (res > 0) {
                resOfpf = userDao.setIsProfile(userId);//设置个人信息完善
                String succMsg = "更新个人资料成功！";
                request.getSession().setAttribute("successMsg", succMsg);
            } else {
                String errorMsg = "更新个人资料失败！";
                request.getSession().setAttribute("errorMsg", errorMsg);
            }
            response.sendRedirect("user?method=profile&id="+userId);
        }else if(method.equals("bloginfo")){//编辑博客信息
            userId = Integer.parseInt(request.getParameter("userId"));
            bi = blogInfoDao.getByuserId(userId);//根据userId获取博客信息
            request.setAttribute("bi", bi);
            request.getRequestDispatcher("front/BlogInfo.jsp").forward(request, response);
        }else if(method.equals("updatebloginfo")){//更新个人博客信息
            response.setContentType("text/html; charset=UTF-8");
            request.setCharacterEncoding("UTF-8");
            userId = Integer.parseInt(request.getParameter("userId"));
            blogName = request.getParameter("blog_name");
            String description = request.getParameter("description");
            String propagate = request.getParameter("propagate");
            int res = blogInfoDao.updateBlogInfo(userId, blogName, description, propagate);//更新个人博客信息
            if (res > 0) {    //更新博客信息成功
                request.getSession().setAttribute("succUpdateMsg", "更新博客信息成功！");
            } else {
                request.getSession().setAttribute("errorUpdateMsg", "更新博客信息失败！");
            }
            response.sendRedirect("user?method=bloginfo&userId="+userId);
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }


}
